#!/usr/bin/ruby

require "rubygems"
require "eventmachine"

module ChatServer
	def self.list
		@list ||= []
	end

	# This function is called whenever someone connections. We assign them a random name
	# and append them to the global user list. This is a "callback function", in that this
	# function is automatically called whenever someone joins.
	def post_init
		@name = "anonymous_#{rand(99999)}"
		ChatServer.list.each{ |c| c.send_data "#@name} has joined.\n"}
		ChatServer.list << self
	end

	# This is called whenever someone disconnects. We just remove them and send a message
	# that they left.
	def unbind
		ChatServer.list.delete self
		ChatServer.list.each{ |c| c.send_data "#{@name} has left. \n" }
	end

	# THis is called whenever data is received. I am not EXACTLY sure what is happening here
	# since I am not familiar with Ruby syntax, but it looks like data is aggregated until it
	# finds a \n, the traditional line termination character used in telnet programs.
	# We then check the beginning of the line for a / command using a regex. This is where you
	# would put most of your logic code.
	def receive_data data
		(@buf ||= '') << data
		while line = @buf.slice!(/(.+)\r?\n/)
			if line =~ %r|^/nick (.+)|
				new_name = $1.strip
				(ChatServer.list - [self]).each{ |c| c.send_data "#{@name} is nown known as #{new_name}\n" }
				@name = new_name
			elsif line =~ %r|^/quit|
				close_connection
			else
				(ChatServer.list - [self]).each{ |c| c.send_data "#{@name}: #{line}"}
			end
		end
	end
end

EM.run {
	EM.start_server '0.0.0.0', 8081, ChatServer
}
